package main

import (
	. "challenge/src"
	"context"
	"encoding/json"
	"fmt"
	"net/http"

	"github.com/aws/aws-sdk-go-v2/config"
	"github.com/aws/aws-sdk-go-v2/credentials"
	"github.com/aws/aws-sdk-go-v2/service/sns"
	"github.com/go-chi/chi/v5"
	"github.com/go-chi/chi/v5/middleware"
	"github.com/go-chi/render"
)

func main() {
	r := chi.NewRouter()
	r.Use(middleware.Logger)
	r.Get("/", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("welcome"))
	})
	r.Post("/user", store)
	r.Get("/user/{id}", show)
	http.ListenAndServe(":8080", r)
}

//store a single user
func store(w http.ResponseWriter, r *http.Request) {
	data := &UserRequest{}
	if err := render.Bind(r, data); err != nil {
		render.Render(w, r, ErrInvalidRequest(err))
		return
	}
	if err := DbHelper.Table("user").Create(data).Error; err != nil {
		render.Render(w, r, ErrRender(err))
	}
	//push msg to SNS
	fmt.Println(data)
	jsonData, _ := json.Marshal(data)
	push(jsonData)
	render.Render(w, r, &Resp{Code: 200, Msg: "success", Data: data})
}

//get single user by id from url
func show(w http.ResponseWriter, r *http.Request) {
	id := chi.URLParam(r, "id")
	user := &User{}
	DbHelper.Table("user").Where("id", id).First(user)
	fmt.Println(user)
	render.Render(w, r, user)
}

//推送
func push(data []byte) {
	msg := string(data)
	topicARN := "arn:aws:sns:ap-east-1:863376839233:goChallenge"

	cfg, err := config.LoadDefaultConfig(context.TODO(),
		config.WithCredentialsProvider(credentials.NewStaticCredentialsProvider("AKIA4SBKFCJAXUOUXUN2", "EF6NR+AagJPE2QeDVxuKPuh9XRomOd0MDK1+8kOK", "")),
		config.WithRegion("ap-east-1"), //这里必须写，否则报错
	)

	client := sns.NewFromConfig(cfg)

	input := &sns.PublishInput{
		Message:  &msg,
		TopicArn: &topicARN,
	}

	result, err := PublishMessage(context.TODO(), client, input)
	if err != nil {
		fmt.Println("Got an error publishing the message:")
		fmt.Println(err)
		return
	}

	fmt.Println("Push success, message id: " + *result.MessageId)
}
